// 定义图表数据存储
const processingTimeData = {
    labels: [],
    datasets: [{
        label: '平均处理时间 (s)',
        data: [],
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
    }]
};

const queueSizeData = {
    labels: [],
    datasets: [{
        label: '请求队列大小',
        data: [],
        borderColor: 'rgb(255, 99, 132)',
        tension: 0.1
    }]
};

const endToEndTimeData = {
    labels: [],
    datasets: [{
        label: '平均处理时间 (s)',
        data: [],
        borderColor: 'rgb(54, 162, 235)', // Blue color
        tension: 0.1
    }]
};

// 获取 canvas 元素
const queueSizeCtx = document.getElementById('queueSizeChart').getContext('2d');
const endToEndTimeCtx = document.getElementById('endToEndTimeChart').getContext('2d');

// 初始化图表
const queueSizeChart = new Chart(queueSizeCtx, {
    type: 'line',
    data: queueSizeData,
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

const endToEndTimeChart = new Chart(endToEndTimeCtx, {
    type: 'line',
    data: endToEndTimeData,
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// 异步获取性能数据并更新图表
async function fetchPerformanceData() {
    try {
        const response = await fetch('/api/performance'); // 假设 FastAPI 运行在同一域下
        const data = await response.json();

        const now = new Date().toLocaleTimeString();

        // 更新队列大小图表
        queueSizeData.labels.push(now);
        queueSizeData.datasets[0].data.push(data.current_queue_size);
        if (queueSizeData.labels.length > 20) {
            queueSizeData.labels.shift();
            queueSizeData.datasets[0].data.shift();
        }
        queueSizeChart.update();

        // 更新平均端到端处理时间图表
        endToEndTimeData.labels.push(now);
        endToEndTimeData.datasets[0].data.push(data.average_end_to_end_time);
        if (endToEndTimeData.labels.length > 20) {
            endToEndTimeData.labels.shift();
            endToEndTimeData.datasets[0].data.shift();
        }
        endToEndTimeChart.update();

        // 更新实时指标
        document.getElementById('processedCount').textContent = data.processed_count;
        document.getElementById('successfulCount').textContent = data.successful_count;
        document.getElementById('failedCount').textContent = data.failed_count;

    } catch (error) {
        console.error('获取性能数据失败:', error);
    }
}

// 每 5 秒更新一次数据
setInterval(fetchPerformanceData, 5000);

// 页面加载时立即获取一次数据
fetchPerformanceData();

// --- 调用列表功能 --- START

// 模拟调用数据
let allCalls = [
    {
        bh: "XF001",
        startTime: "2023-10-26 10:00:00",
        status: "成功",
        processTime: 120,
        requestInfo: { method: "POST", url: "/api/submit", payload: { id: 1, type: "complaint" } },
        responseInfo: { status: 200, message: "Success" },
        errorInfo: null
    },
    {
        bh: "XF002",
        startTime: "2023-10-26 10:05:00",
        status: "失败",
        processTime: 250,
        requestInfo: { method: "GET", url: "/api/query", params: { queryId: 123 } },
        responseInfo: null,
        errorInfo: { code: 500, message: "Internal Server Error", details: "Database connection failed" }
    },
    {
        bh: "XF003",
        startTime: "2023-10-25 11:15:00",
        status: "成功",
        processTime: 80,
        requestInfo: { method: "PUT", url: "/api/update", payload: { id: 2, status: "resolved" } },
        responseInfo: { status: 200, message: "Updated" },
        errorInfo: null
    },
    {
        bh: "XF004",
        startTime: "2023-10-26 10:30:00",
        status: "成功",
        processTime: 90,
        requestInfo: { method: "GET", url: "/api/report", params: { date: "2023-10-26" } },
        responseInfo: { status: 200, data: "report_data" },
        errorInfo: null
    },
    {
        bh: "XF005",
        startTime: "2023-10-24 09:00:00",
        status: "失败",
        processTime: 300,
        requestInfo: { method: "POST", url: "/api/auth", payload: { user: "test" } },
        responseInfo: null,
        errorInfo: { code: 401, message: "Unauthorized", details: "Invalid credentials" }
    }
];

let currentCalls = [...allCalls]; // 用于存储当前显示的调用数据

// 获取DOM元素
const queryDateInput = document.getElementById('queryDate');
const queryBhInput = document.getElementById('queryBh');
const queryStatusSelect = document.getElementById('queryStatus');
const searchButton = document.getElementById('searchBtn');
const resetButton = document.getElementById('resetBtn');
const callListTableBody = document.getElementById('callListTableBody');
const detailModal = document.getElementById('detailModal');
const closeButton = detailModal.querySelector('.close-button');

const detailBh = document.getElementById('detailBh');
const detailStartTime = document.getElementById('detailStartTime');
const detailStatus = document.getElementById('detailStatus');
const detailProcessTime = document.getElementById('detailProcessTime');
const detailRequest = document.getElementById('detailRequest');
const detailResponse = document.getElementById('detailResponse');
const detailErrorSection = document.getElementById('detailErrorSection');
const detailError = document.getElementById('detailError');

// 分页相关DOM元素
const itemsPerPageSelect = document.getElementById('itemsPerPage');
const prevPageBtn = document.getElementById('prevPageBtn');
const nextPageBtn = document.getElementById('nextPageBtn');
const pageInfoSpan = document.getElementById('pageInfo');

// 分页状态
let currentPage = 1;
let itemsPerPage = parseInt(itemsPerPageSelect.value); // 初始值从select中获取
let totalPages = 1;
let allFilteredCalls = []; // 存储所有经过筛选但未分页的调用数据

// 渲染调用列表
function renderCallList(calls) {
    callListTableBody.innerHTML = ''; // 清空现有内容
    if (calls.length === 0) {
        callListTableBody.innerHTML = '<tr><td colspan="6" style="text-align: center;">无数据显示</td></tr>';
        return;
    }

    calls.forEach((call, idx) => {
        const row = callListTableBody.insertRow();
        row.insertCell().textContent = idx + 1; // 每页从1开始
        row.insertCell().textContent = call.bh;
        row.insertCell().textContent = call.startTime;

        const statusCell = row.insertCell();
        statusCell.textContent = call.status;
        statusCell.classList.add(call.status === '成功' ? 'status-success' : 'status-failed');

        row.insertCell().textContent = call.processTime.toFixed(2) + ' s';

        const actionCell = row.insertCell();
        const detailButton = document.createElement('button');
        detailButton.textContent = '查看详情';
        detailButton.classList.add('action-btn');
        detailButton.onclick = () => showCallDetail(call);
        actionCell.appendChild(detailButton);
    });
}

// 更新分页控件状态
function updatePaginationControls() {
    totalPages = Math.ceil(allFilteredCalls.length / itemsPerPage);
    pageInfoSpan.textContent = `${currentPage} / ${totalPages}`;

    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
}

// 显示调用详情模态框
function showCallDetail(call) {
    detailBh.textContent = call.bh;
    detailStartTime.textContent = call.startTime;
    detailStatus.textContent = call.status;
    detailStatus.classList.remove('status-success', 'status-failed');
    detailStatus.classList.add(call.status === '成功' ? 'status-success' : 'status-failed');
    detailProcessTime.textContent = call.processTime.toFixed(2) + ' s';

    detailRequest.textContent = JSON.stringify(call.requestInfo, null, 2);
    detailResponse.textContent = call.responseInfo ? JSON.stringify(call.responseInfo, null, 2) : '无响应信息';

    if (call.errorInfo) {
        detailError.textContent = JSON.stringify(call.errorInfo, null, 2);
        detailErrorSection.style.display = 'block';
    } else {
        detailErrorSection.style.display = 'none';
    }

    detailModal.style.display = 'block';
}

// 隐藏模态框
closeButton.onclick = () => {
    detailModal.style.display = 'none';
};

window.onclick = (event) => {
    if (event.target == detailModal) {
        detailModal.style.display = 'none';
    }
};

// 增加 resetPage 参数，默认为 false
async function fetchCallData(resetPage = false) {
    const queryDate = queryDateInput.value;
    const queryBh = queryBhInput.value;
    const queryStatus = queryStatusSelect.value;

    let url = '/api/calls';
    const params = new URLSearchParams();

    if (queryDate) params.append('date', queryDate);
    if (queryBh) params.append('bh', queryBh);
    if (queryStatus) params.append('status', queryStatus);

    if (params.toString()) url += `?${params.toString()}`;

    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const result = await response.json();
        if (result.success) {
            allFilteredCalls = result.data;
            if (resetPage) currentPage = 1; // 只有主动查询或重置时才回到第一页
            updatePaginationAndRender();
        } else {
            allFilteredCalls = [];
            updatePaginationAndRender();
        }
    } catch (error) {
        allFilteredCalls = [];
        updatePaginationAndRender();
    }
}

// 根据当前分页状态渲染列表并更新控件
function updatePaginationAndRender() {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const callsToRender = allFilteredCalls.slice(startIndex, endIndex);
    renderCallList(callsToRender);
    updatePaginationControls();
}

// 绑定分页事件
itemsPerPageSelect.addEventListener('change', () => {
    itemsPerPage = parseInt(itemsPerPageSelect.value);
    currentPage = 1; // 改变每页显示数量时，回到第一页
    updatePaginationAndRender();
});

prevPageBtn.addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        updatePaginationAndRender();
    }
});

nextPageBtn.addEventListener('click', () => {
    if (currentPage < totalPages) {
        currentPage++;
        updatePaginationAndRender();
    }
});

// 搜索按钮
searchButton.addEventListener('click', () => fetchCallData(true));

// 重置按钮
resetButton.addEventListener('click', () => {
    queryDateInput.value = '';
    queryBhInput.value = '';
    queryStatusSelect.value = '';
    fetchCallData(true);
});

// 页面加载时立即渲染一次列表
fetchCallData(false);

// 每 5 秒更新一次调用列表数据
setInterval(() => fetchCallData(false), 5000);

// --- 调用列表功能 --- END 